<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>扫码登录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .qr-login-container {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            max-width: 500px;
            width: 100%;
            text-align: center;
        }

        .header {
            margin-bottom: 30px;
        }

        .title {
            font-size: 28px;
            font-weight: bold;
            color: #333;
            margin-bottom: 8px;
        }

        .subtitle {
            font-size: 16px;
            color: #666;
        }

        .qr-section {
            margin-bottom: 30px;
        }

        .qr-wrapper {
            margin-bottom: 20px;
        }

        .qr-code {
            width: 200px;
            height: 200px;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }

        .qr-code:hover {
            transform: scale(1.05);
        }

        .qr-loading {
            width: 200px;
            height: 200px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #666;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 15px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .status-message {
            margin-bottom: 20px;
        }

        .status-text {
            display: inline-flex;
            align-items: center;
            font-size: 14px;
            padding: 12px 20px;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .status-text .icon {
            margin-right: 8px;
            font-size: 16px;
        }

        .status-text.pending {
            background: #e3f2fd;
            color: #1976d2;
        }

        .status-text.scanned {
            background: #e8f5e8;
            color: #388e3c;
        }

        .status-text.confirmed {
            background: #e8f5e8;
            color: #388e3c;
            font-weight: bold;
        }

        .status-text.expired {
            background: #ffebee;
            color: #d32f2f;
        }

        .countdown {
            font-size: 12px;
            color: #666;
            margin-bottom: 15px;
        }

        .actions {
            margin-bottom: 20px;
        }

        .btn {
            padding: 12px 24px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 0 5px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
        }

        .btn-secondary:hover {
            background: #f5f5f5;
        }

        .user-info {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin-top: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .user-avatar {
            margin-right: 15px;
        }

        .user-avatar img {
            width: 50px;
            height: 50px;
            border-radius: 25px;
            border: 3px solid #667eea;
        }

        .user-details {
            text-align: left;
        }

        .username {
            display: block;
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 4px;
        }

        .user-id {
            display: block;
            font-size: 12px;
            color: #666;
        }

        .hidden {
            display: none;
        }

        @media (max-width: 480px) {
            .qr-login-container {
                padding: 20px;
            }
            
            .qr-code {
                width: 150px;
                height: 150px;
            }
            
            .qr-loading {
                width: 150px;
                height: 150px;
            }
        }
    </style>
</head>
<body>
    <div class="qr-login-container">
        <!-- 头部 -->
        <div class="header">
            <h1 class="title">扫码登录</h1>
            <p class="subtitle">使用微信小程序扫码快速登录</p>
        </div>

        <!-- 二维码区域 -->
        <div class="qr-section">
            <div class="qr-wrapper">
                <img id="qrcode" class="qr-code hidden" alt="登录二维码" />
                <div id="qr-loading" class="qr-loading">
                    <div class="loading-spinner"></div>
                    <span>正在生成二维码...</span>
                </div>
            </div>
            
            <!-- 状态提示 -->
            <div class="status-message">
                <div id="status-text" class="status-text pending">
                    <span class="icon">📱</span>
                    请使用微信扫描二维码登录
                </div>
            </div>

            <!-- 倒计时 -->
            <div id="countdown" class="countdown hidden">
                二维码将在 <span id="countdown-time">300</span> 秒后过期
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="actions">
            <button id="generate-btn" class="btn btn-primary" onclick="generateQRCode()">
                生成二维码
            </button>
            <button id="refresh-btn" class="btn btn-secondary hidden" onclick="refreshQRCode()">
                刷新二维码
            </button>
        </div>

        <!-- 登录成功后的用户信息 -->
        <div id="user-info" class="user-info hidden">
            <div class="user-avatar">
                <img id="user-avatar" src="/images/default-avatar.png" alt="用户头像" />
            </div>
            <div class="user-details">
                <span id="username" class="username">用户名</span>
                <span id="user-id" class="user-id">ID: 0</span>
            </div>
        </div>
    </div>

    <script>
        let pollInterval;
        let countdownInterval;
        let sessionId = '';
        let countdown = 0;

        // 页面加载时生成二维码
        document.addEventListener('DOMContentLoaded', function() {
            generateQRCode();
        });

        // 生成二维码
        async function generateQRCode() {
            showLoading();
            hideUserInfo();
            
            try {
                const response = await fetch('/api/v1/auth/qrcode/generate', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });

                if (!response.ok) {
                    throw new Error('生成二维码失败');
                }

                const data = await response.json();
                sessionId = data.session_id;
                countdown = data.expires_in;

                // 显示二维码
                const qrCodeImg = document.getElementById('qrcode');
                qrCodeImg.src = data.qr_code;
                qrCodeImg.classList.remove('hidden');
                document.getElementById('qr-loading').classList.add('hidden');

                // 更新状态
                updateStatus('pending', '📱', '请使用微信扫描二维码登录');
                
                // 开始轮询和倒计时
                startPolling();
                startCountdown();
                
                // 更新按钮状态
                updateButtonState('pending');
                
            } catch (error) {
                console.error('生成二维码失败:', error);
                updateStatus('expired', '❌', '生成二维码失败，请重试');
                updateButtonState('expired');
            }
        }

        // 刷新二维码
        function refreshQRCode() {
            clearIntervals();
            generateQRCode();
        }

        // 开始轮询登录状态
        function startPolling() {
            if (pollInterval) {
                clearInterval(pollInterval);
            }

            pollInterval = setInterval(async () => {
                await checkLoginStatus();
            }, 2000);
        }

        // 检查登录状态
        async function checkLoginStatus() {
            if (!sessionId) return;

            try {
                const response = await fetch(`/api/v1/auth/qrcode/status/${sessionId}`);
                
                if (!response.ok) {
                    throw new Error('检查状态失败');
                }

                const status = await response.json();

                switch (status.status) {
                    case 'scanned':
                        updateStatus('scanned', '✅', '已扫码，请在小程序中确认登录');
                        break;

                    case 'confirmed':
                        handleLoginSuccess(status);
                        break;

                    case 'expired':
                        handleQRExpired();
                        break;
                }
            } catch (error) {
                console.error('检查登录状态失败:', error);
            }
        }

        // 处理登录成功
        function handleLoginSuccess(loginData) {
            clearIntervals();
            
            // 保存登录信息到localStorage
            localStorage.setItem('userInfo', JSON.stringify(loginData.user));
            localStorage.setItem('accessToken', loginData.access_token);
            localStorage.setItem('tokenType', loginData.token_type);
            
            // 更新界面
            updateStatus('confirmed', '🎉', '登录成功！');
            showUserInfo(loginData.user);
            updateButtonState('confirmed');
            
            // 延迟跳转
            setTimeout(() => {
                window.location.href = '/dashboard';
            }, 2000);
        }

        // 处理二维码过期
        function handleQRExpired() {
            clearIntervals();
            
            updateStatus('expired', '⏰', '二维码已过期，请重新生成');
            updateButtonState('expired');
            hideQRCode();
        }

        // 开始倒计时
        function startCountdown() {
            if (countdownInterval) {
                clearInterval(countdownInterval);
            }

            const countdownElement = document.getElementById('countdown-time');
            const countdownContainer = document.getElementById('countdown');
            countdownContainer.classList.remove('hidden');

            countdownInterval = setInterval(() => {
                if (countdown > 0) {
                    countdown--;
                    countdownElement.textContent = countdown;
                } else {
                    handleQRExpired();
                }
            }, 1000);
        }

        // 清除所有定时器
        function clearIntervals() {
            if (pollInterval) {
                clearInterval(pollInterval);
                pollInterval = null;
            }
            
            if (countdownInterval) {
                clearInterval(countdownInterval);
                countdownInterval = null;
            }
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('qrcode').classList.add('hidden');
            document.getElementById('qr-loading').classList.remove('hidden');
            updateStatus('pending', '⏳', '正在生成二维码...');
        }

        // 隐藏二维码
        function hideQRCode() {
            document.getElementById('qrcode').classList.add('hidden');
            document.getElementById('qr-loading').classList.remove('hidden');
        }

        // 更新状态
        function updateStatus(status, icon, message) {
            const statusElement = document.getElementById('status-text');
            statusElement.className = `status-text ${status}`;
            statusElement.innerHTML = `<span class="icon">${icon}</span>${message}`;
        }

        // 更新按钮状态
        function updateButtonState(status) {
            const generateBtn = document.getElementById('generate-btn');
            const refreshBtn = document.getElementById('refresh-btn');
            const countdownContainer = document.getElementById('countdown');

            switch (status) {
                case 'pending':
                    generateBtn.classList.add('hidden');
                    refreshBtn.classList.remove('hidden');
                    countdownContainer.classList.remove('hidden');
                    break;
                case 'expired':
                    generateBtn.classList.remove('hidden');
                    refreshBtn.classList.add('hidden');
                    countdownContainer.classList.add('hidden');
                    break;
                case 'confirmed':
                    generateBtn.classList.add('hidden');
                    refreshBtn.classList.add('hidden');
                    countdownContainer.classList.add('hidden');
                    break;
            }
        }

        // 显示用户信息
        function showUserInfo(user) {
            const userInfo = document.getElementById('user-info');
            const username = document.getElementById('username');
            const userId = document.getElementById('user-id');
            const userAvatar = document.getElementById('user-avatar');

            username.textContent = user.nickname || user.username;
            userId.textContent = `ID: ${user.id}`;
            if (user.avatar) {
                userAvatar.src = user.avatar;
            }

            userInfo.classList.remove('hidden');
        }

        // 隐藏用户信息
        function hideUserInfo() {
            document.getElementById('user-info').classList.add('hidden');
        }

        // 页面卸载时清除定时器
        window.addEventListener('beforeunload', function() {
            clearIntervals();
        });
    </script>
</body>
</html> 